<?php


namespace app\api\service;


use app\api\model\User;
use app\lib\exception\UserException;
use think\Exception;

class DeliveryMessage{

    protected $tplID;
    protected $page;
    protected $formID;
    protected $data;
    protected $emphasisKeyWord;
    protected $url;

    private $sendUrl = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=%s";

    //获取模板id
    //获取access_token
    //拼装发送的数据

    public function __construct(){
        $AccessToken = new AccessToken();
        $access_token = $AccessToken->getToken();
        $this->tplID = '-ves57ARR1k_0U-coXW6vHdCohILpUt0lPuNtl6KhFA';
        $this->sendUrl = sprintf($this->sendUrl,$access_token);
    }

    public function sendDeliveryMessage($order,$jumpPage){
        $data = [
            'touser' => $this->getUserOpenid($order->user_id),
            'template_id' => $this->tplID,
            'form_id' => $order->prepay_id,
            'data' => $this->preData($order),
        ];
        $result = https_request($this->sendUrl,json_encode($data));
        $result = json_decode($result, true);
        if ($result['errcode'] == 0) {
            return true;
        } else {
            throw new Exception('模板消息发送失败,  ' . $result['errmsg']);
        }
    }

    //拼装关键字
    private  function preData($order){
        $data = [
            'keyword1' => [
                'value' => '顺风速运',
            ],
            'keyword2' => [
                'value' => $order->snap_name,
                'color' => '#27408B'
            ],
            'keyword3' => [
                'value' => $order->order_no
            ],
            'keyword4' => [
                'value' => date('Y-m-d H:i:s',time())
            ]
        ];
        return $data;
    }

    //获取openid
    private function getUserOpenid($uid){
        $userToken = new User();
        $user = $userToken::get($uid);
        if(!$user){
            throw new UserException();
        }
        return $user->openid;
    }

}



